<?php
header("content-Type: text/html; charset=Utf-8");
/**
 * @version        $Id: excel.class.php 2014年8月20日Z yeshili $
 * @package        YeshiliCMS.Admin
 * @copyright      Copyright (c) 2014 - 2050, YeshiliCMS, Inc.
 * @license        http://help.****.com/YeshiliCMS/help.html
 * @link           http://www.****.com
 */
//导出到excel文件(一般导出中文的都会乱码，需要进行编码转换）
//使用方法如下
/*$excel = new Excel();
$excel->addHeader(array('列1','列2','列3','列4','列5'),'客户关系管理系统');
$excel->addBody(
            array(
                array('数据1','数据2','数据3','数据4','数据5'),
                array('数据1','数据2','数据3','数据4','数据5'),
                array('数据1','数据2','数据3','数据4','数据5'),
                array('数据1','数据2','数据3','数据4','数据5')
            )
        );
$excel->downLoad();
*/
class Excel{
    private $head;
    private $body;
    /**
     * 
     * @param type $arr 一维数组
     */
	public function addHeader($arr,$title){
		$this->head .= "<tr height='30' style='font-weight:bold;' align='center'><td colspan='".count($arr)."'>".$title."</td></tr>";
		$this->head .= "<tr height='30' style='font-weight:bold;' align='center'>";
        foreach($arr as $headVal){
            $headVal = $headVal;
            $this->head .= "<td>{$headVal}</td>";
        }
        $this->head .= "</tr>";
    }
     
    /**
     * 
     * @param type $arr 二维数组
     */
    public function addBody($arr){
        foreach($arr as $arrBody){
			$this->body .="<tr height='24' align='center'>";
            foreach($arrBody as $bodyVal){
                $bodyVal = $bodyVal;
                $this->body .= "<td>{$bodyVal}</td>";
            }
            $this->body .= "</tr>";
        }
    }
     
    /**
     * 下载excel文件
     */
    public function downLoad($filename=''){
        if(!$filename)
            $filename = date('YmdHis',time()).'.xls';
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=$filename"); 
        header("Content-Type:charset=utf-8");
        if($this->head)
		echo "<table border='1'>";
        echo $this->head;
        echo $this->body;
		echo "</table>";
    }
     
    /**
     * 编码转换
     * @param type $string
     * @return string
     */
    public function charset($string){
        return iconv("utf-8", "gb2312", $string);
    }
}
?>